﻿using System;
using System.Web;
using System.Web.Mvc;

namespace CodeContrib.Web.Mvc
{
	[AttributeUsage(AttributeTargets.Class | AttributeTargets.Method, Inherited = true, AllowMultiple = true)]
	public class CacheAttribute : ActionFilterAttribute
	{
		public int Duration { get; set; }

		public CacheAttribute()
		{
			Duration = 10;
		}

		public override void OnActionExecuted(ActionExecutedContext filterContext)
		{
			if (Duration <= 0)
			{
				return;
			}

			var cacheDuration = TimeSpan.FromSeconds(Duration);

			var cache = filterContext.HttpContext.Response.Cache;
			cache.AppendCacheExtension("must-revalidate, proxy-revalidate");
			cache.SetCacheability(HttpCacheability.Public);
			cache.SetExpires(DateTime.Now.Add(cacheDuration));
			cache.SetMaxAge(cacheDuration);
		}
	}
}